<template>
  <xy-page>
    <xy-search>
      <el-form>
        <el-form-item>
          <el-input class="chanlNum" placeholder="频道号" v-model="chanlNum" clearable oninput="this.value=this.value.replace(/[^0-9]/g,'')" v-show="!(userType==2)"></el-input>
            <el-date-picker
              v-model="pickTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="betweenDays"
              :picker-options="pickerOptions"
              clearable
            ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="right">
        <el-button type="primary" @click="search">查询</el-button>
        <el-button plain @click="resetForm">重置条件</el-button>
      </div>
    </xy-search>
    <div>
      <ul class="topCountUl">
        <li>
          <div>最高并发（人）</div>
          <div>{{maxNum}}</div>
        </li>
        <li>
          <div>观看次数（次）</div>
          <div>{{viewTimes}}</div>
        </li>
        <li>
          <div>观看时长（分钟）</div>
          <div>{{longTime}}</div>
        </li>
        <li>
          <div>观看ip数（UV）</div>
          <div>{{ipNum}}</div>
        </li>
      </ul>
    </div>
    <el-tabs v-model="activeTab" @tab-click="getTabData">
      <el-tab-pane label="观看日志" name="观看日志">
        <el-button type="success" @click="logsDownload" style="margin-bottom:10px;">导出数据</el-button>
        <xy-table :tableData="tabledata" :loading="tabledata.isLoading" @change="getLogsList" :noEmpty="!tabledata.list">
          <el-table-column label="用户昵称" align="center" min-width="80" prop="userName"></el-table-column>
          <el-table-column prop="watchId" label="用户ID" align="center" min-width="130"></el-table-column>
          <el-table-column label="观看地址" align="center">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.referer" placement="top" effect="dark">
                <span>{{scope.row.referer}}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="session" label="直播场次" align="center" min-width="110"></el-table-column>
          <el-table-column label="直播/回放" align="center" min-width="80">
            <template slot-scope="scope">
              {{scope.row.type=='live'?'直播':'回放'}}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="观看时长" align="center" min-width="80"></el-table-column>
          <el-table-column prop="enterDate" label="进入时间" align="center" min-width="150"></el-table-column>
          <el-table-column prop="city" label="地区" align="center" min-width="50"></el-table-column>
          <el-table-column prop="ipAddress" label="观众IP" align="center" min-width="130"></el-table-column>
          <el-table-column prop="terminal" label="观看终端" align="center" min-width="80"></el-table-column>
          <el-table-column prop="firsetTime" label="首次签到时间">
            <template slot-scope="scope">
              {{scope.row.firsetTime || '--'}}
            </template>
          </el-table-column>
          <el-table-column prop="lastTime" label="最后签到时间">
            <template slot-scope="scope">
              {{scope.row.lastTime || '--'}}
            </template>
          </el-table-column>
          <el-table-column prop="num" label="总签到次数"></el-table-column>
        </xy-table>
        <div style="position:relative;top:-130px;text-align:center;" v-show="noData">暂无数据</div>
      </el-tab-pane>
      <!-- 地域分布 -->
      <el-tab-pane label="地域分布" name="地域分布">
        <div class="chartContain">
          <div id="areaCount"></div>
          <div id="countDetail">
            <span>Top 10省市占比</span>
            <el-table :data="topTenData.list">
              <el-table-column label="省份或直辖市" prop="province"></el-table-column>
              <el-table-column label="观看人数" prop="viewer"></el-table-column>
              <el-table-column label="占比" prop="percent"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      <!-- 终端分布 -->
      <el-tab-pane label="终端分布" name="终端分布">
        <div class="chartContain">
          <div id="terminCount"></div>
          <div id="countDetail">
            <el-table :data="terminData.seriesData">
              <el-table-column label="观看终端" prop="name"></el-table-column>
              <el-table-column label="观看人数" prop="value"></el-table-column>
              <el-table-column label="占比" prop="percent"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="在线并发" name="在线并发">
        <!-- 在线并发 -->
        <div id="onlineNum"></div>
        <div style="position:relative;top:-230px;text-align:center;" v-show="noData">暂无数据</div>
      </el-tab-pane>
    </el-tabs>
  </xy-page>
</template>

<script>
export default {
  data() {
    return {
      appId:'',
      userType:'',
      noData:true,
      sessionKey:'',
      pickerOptions: this.$utils.disabledDate(),
      areaCount:'',
      terminCount:'',
      onlineNum:'',
      concurTitleData:{
        day:'00-00-00',
        minute:'00：00',
        viewers:0
      },
      logsDetailData:{
        downloaded:false
      },
      terminDetailData:{
        downloaded:false
      },
      concurDetailData:{
        downloaded:false
      },
      allProData:{
        list:[]
      },
      areaDetailData:{
        downloaded:false
      },
      concurTitle:{
        day:'00-00-00',
        minute:'00：00',
        viewers:0
      },
      terminData: {
        total:0,
        lengendData: [],
        seriesData: []
      },
      topTenData:{
        isloading:false,
        list:[]
      },
      concurrenceData:{
        concurLoaded:false,
      },
      oldChanlNum:'',
      tabledata: {
        isLoading:false,
        total:0,
        size:10,
        page:1,
        list: []
      },
      chanlNum: '',
      activeTab: "观看日志",
      oldPickTime:[],
      pickTime: [],
      viewTimes: 0,
      longTime: 0,
      ipNum: 0,
      province: "~~",
      terminal: "",
      maxNum: 0,
      options: [],
      onlineData: {
        xData: [],
        seriesData: []
      },
      areaData: {
        total:0,
        legendData: [],
        seriesData: []
      }
    };
  },
  mounted() {
    this.appId = sessionStorage.getItem('curAccountAppId')
    this.userType = sessionStorage.getItem('userType')
    this.sessionKey = JSON.parse(sessionStorage.getItem('UserInfo')).sessionKey
    this.$root.eventHandle.$emit("UPDATE_MENU")
    this.pickTime = [new Date(),new Date()]
    this.chanlNum = sessionStorage.getItem('dataChannelId')
    if(this.chanlNum){
      this.search()
    }
  },
  methods: {
    betweenDays(){
      if(!this.pickTime)return
      if(this.pickTime[1].getMonth()!=this.pickTime[0].getMonth()){
        this.$message.error('时间不能跨月')
        this.pickTime = []
        return
      }
    },
    logsDownload(){
      if(!this.tabledata.list.length){
        this.$message.error('当前无数据')
        return
      }
      this.$utils.linkTo(
        this.$utils.getUrl('/admin/instance/ccb/polyv/channel/viewLog/export.do',{
          channelId:this.chanlNum,
          endTime:this.oldPickTime[1].getTime(),
          startTime:this.oldPickTime[0].getTime(),
          'session-key':this.sessionKey,
          page:1,
          pageSize:100000,
          appId:this.appId
        })
      )
    },
    areaCharts(){
      // 地域分布饼图
      var areaOpt = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          orient: "vertical",
          right: 50,
          top: 50,
          data:  this.areaData.legendData
        },
        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: "60%",
            center: ["50%", "50%"],
            data: this.areaData.seriesData,
            labelLine:{
              length:20,
              length2:10
            }
          }
        ]
      };
      if(!this.areaCount){
        this.areaCount = this.$echarts.init(document.getElementById("areaCount"));
      }
      this.areaCount.setOption(areaOpt);
    },
    termCharts(){
      // 终端分布饼图
      var terminOpt = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: 'scroll',
          top: 10,
          data:  this.terminData.lengendData
        },
        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: "60%",
            center: ["50%", "50%"],
            data:this.terminData.seriesData,
            labelLine:{
              length:20,
              length2:10
            }
          }
        ]
      };
      if(!this.terminCount){
        this.terminCount = this.$echarts.init(document.getElementById("terminCount"));
      }
      this.terminCount.setOption(terminOpt);
    },
    onlineCharts(){
      // 在线并发
      var onlineOpt = {
        title: {
          left: "center",
          text:  "最高并发观看人数："+this.concurTitleData.viewers+" [时间："+this.concurTitleData.day+" "+this.concurTitleData.minute+"]"
        },
        legend: {
          left: "left",
          data: ["观看人数"]
        },
        tooltip : {
          trigger: 'axis'
        },
        xAxis: {
          data:this.onlineData.xData,
          splitLine: {
            show: true
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          name: "观看人数",
          type: "value",
          splitLine: {
            show: true
          }
        },
        series: [
          {
            name: "观看人数",
            data: this.onlineData.seriesData,
            type: "line"
          }
        ],
        dataZoom: [
          {
            type: "slider",
            show: true,
            start: 0, // 从start到end总共分成100份
            end: 100,
          },
          {
            type: "inside",
            start: 10,
            end: 90
          }
        ],
        grid:{
          bottom:70
        }
      };
      if(!this.onlineNum){
        this.onlineNum = this.$echarts.init(document.getElementById("onlineNum"));
      }
      this.onlineNum.setOption(onlineOpt);
    },
    getTabData(){
      if(this.oldChanlNum && this.oldPickTime){
        if(this.activeTab == '地域分布'){
          if(this.areaDetailData.downloaded == true)return
          this.getAreaData()
        }else if(this.activeTab == '终端分布'){
          if(this.terminDetailData.downloaded == true)return
          this.getTermData()
        }else if(this.activeTab == '在线并发'){
          if(this.concurDetailData.downloaded == true)return
          this.getConcurData()
        }else if(this.activeTab == '观看日志'){
          if(this.logsDetailData.downloaded == true)return
          this.getLogsList()
        }
      }
    },
    getAreaData(){
      this.$postStream('/admin/instance/ccb/polyv/channel/view/channelGeoStatisSummary.do',{
        data:{
          appId:this.appId,
          channelId: this.oldChanlNum,//oldChanlNum使得在线并发，地域分布，终端分布保持在同一个查询条件下的结果
          startDate: this.$utils.formatDate(this.oldPickTime[0],'yyyy-MM-dd'),
          endDate: this.$utils.formatDate(this.oldPickTime[1],'yyyy-MM-dd')
        },
        success:(res)=>{
          if(res.success){
            sessionStorage.setItem('dataChannelId',this.chanlNum)
            this.areaData.legendData = []
            this.areaData.seriesData  = []
            this.areaData.total = 0
            this.allProData.list = []
            this.topTenData.list = []
            this.areaDetailData.downloaded = true
            if(res.object.length==0)return
            res.object.forEach(item=>{
              this.areaData.legendData.push(item.province)
              this.areaData.seriesData.push({name:item.province,value:item.viewer})
              this.areaData.total += item.viewer
            })
            this.allProData.list = res.object
            for(let i=0;i<this.allProData.list.length-1;i++){
              for(let j=0;j<this.allProData.list.length-1-i;j++){
                if(this.allProData.list[j].viewer>this.allProData.list[j+1].viewer){
                  let temp=this.allProData.list[j]
                  this.allProData.list[j]=this.allProData.list[j+1]
                  this.allProData.list[j+1]=temp
                }
              }
            }
            if(res.object.length<10){
              const len = res.object.length
              for(let i=0;i<len;i++){
                this.topTenData.list.push(this.allProData.list[i])
                this.topTenData.list[i].percent = ((this.topTenData.list[i].viewer/this.areaData.total)*100).toFixed(2)+'%'
              }
            }else{
              for(let i=0;i<10;i++){
                this.topTenData.list.push(this.allProData.list[i])
                this.topTenData.list[i].percent = ((this.topTenData.list[i].viewer/this.areaData.total)*100).toFixed(2)+'%'
              }
            }
            this.areaCharts()
          }else{
            this.$message.error('地域分布数据获取失败')
          }
        },
        error:()=>{
          this.$message.error('地域分布数据获取失败')
        },
        complete:(res)=>{
          if(res.code==-2){
            this.$message.error('频道不存在')
          }
        }
      })
    },
    getTermData(){
      this.$postStream('/admin/instance/ccb/polyv/app/view/channelBrowerStatisSummary.do',{
        data:{
          appId: this.appId,
          channelId:this.oldChanlNum,
          startDate: this.$utils.formatDate(this.oldPickTime[0],'yyyy-MM-dd'),
          endDate: this.$utils.formatDate(this.oldPickTime[1],'yyyy-MM-dd')
        },
        success:(res)=>{
          if(res.success){
            sessionStorage.setItem('dataChannelId',this.chanlNum)
            this.terminData.lengendData = []
            this.terminData.seriesData = []
            this.terminData.total = 0
            res.object.forEach(item=>{
              this.terminData.lengendData.push(item.browser)
              this.terminData.seriesData.push({name:item.browser,value:item.count})
              this.terminData.total += item.count
            })
            for(let i=0;i<res.object.length;i++){
              this.terminData.seriesData[i].percent = ((res.object[i].count/this.terminData.total)*100).toFixed(2)+'%'
            }
            this.terminDetailData.downloaded = true
            this.termCharts()
          }else{
            if(res.code==-2){
              this.$message.error('频道不存在')
            }
          }
        },error:()=>{
          if(res.code==-2){
            this.$message.error('频道不存在')
          }
        }
      })
    },
    getConcurData(){
      this.$postStream('/admin/instance/ccb/polyv/app/view/channelConStatisSummary.do',{
        data:{
          appId:this.appId,
          channelId:this.oldChanlNum,
          startDate: this.$utils.formatDate(this.oldPickTime[0],'yyyy-MM-dd'),
          endDate: this.$utils.formatDate(this.oldPickTime[1],'yyyy-MM-dd')
        },
        success:(res)=>{
          if(res.success){
            sessionStorage.setItem('dataChannelId',this.chanlNum)
            this.onlineData.xData = []
            this.onlineData.seriesData = []
            this.concurDetailData.downloaded = true
            this.concurTitleData.viewers = 0
            this.concurTitleData.day='00-00-00'
            this.concurTitleData.minute='00：00'
            if(!res.object){
            }else{
              if(res.object){
                res.object.forEach(item=>{
                  this.onlineData.xData.push((item.day)+'\n'+(item.minute))
                  this.onlineData.seriesData.push(item.viewers)
                  if(item.viewers>=this.concurTitleData.viewers){
                    this.concurTitleData.viewers = item.viewers
                    this.concurTitleData.day=item.day
                    this.concurTitleData.minute=item.minute
                  }
                })
              }
            }
            this.onlineCharts()
          }else{
            this.$message.error('在线并发数据获取失败')
          }
        },
        error:()=>{
          this.$message.error('在线并发数据获取失败')
        },
        complete:(res)=>{
          if(res.code==-2){
            this.$message.error('频道不存在')
          }
        }
      })
    },
    search() {
      this.noData = false
      this.oldChanlNum = this.chanlNum
      this.oldPickTime = this.pickTime
      this.terminDetailData.downloaded = false
      this.areaDetailData.downloaded = false
      this.concurDetailData.downloaded = false
      this.logsDetailData.downloaded = false
      this.maxNum = 0
      this.longTime = 0
      this.viewTimes = 0
      this.ipNum = 0
      this.tabledata.total = 0
      this.tabledata.list = []
      //地域分布、终端分布、在线并发都以oldChanlNum来请求数据，保证地域分布、终端分布、在线并发和观看日志、统计数据是在同一查询条件下的结果
      if(!this.chanlNum){
        this.$message.error('频道号不能为空')
        return
      }
      this.oldChanlNum = this.chanlNum
      if(!this.pickTime){
        this.$message.error('日期不能为空')
        return
      }
      //统计数据
      this.$postStream('/admin/instance/ccb/polyv/channel/view/channelStatisSummary.do',{
        data:{
          appId:this.appId,
          channelId:this.chanlNum || null,
          startDate:this.$utils.formatDate(this.pickTime[0],'yyyy-MM-dd'),
          endDate:this.$utils.formatDate(this.pickTime[1],'yyyy-MM-dd')
        },
        success:(res)=>{
          if(res.success){ 
            this.maxNum = res.object.concurrenceCount
            this.longTime = res.object.playDuration
            this.viewTimes = res.object.videoView
            this.ipNum = res.object.viewIp
          }else{
            this.$message.error('统计数据获取失败')
          }
        },
        complete:(res)=>{
          if(res.code==-2){
            this.$message.error('频道不存在')
          }
        }
      })
      //观看日志
      if(this.activeTab == '观看日志'){
        this.getLogsList()
      }else if(this.activeTab == '地域分布'){
        this.getAreaData()
      }else if(this.activeTab == '终端分布'){
        this.getTermData()
      }else if(this.activeTab == '在线并发'){
        this.getConcurData()
      }
      
    },
    getLogsList(page){
      if((typeof page) != 'number')page = 1
      this.tabledata.isLoading = true
      this.$postStream('/admin/instance/ccb/polyv/channel/viewLog/list.do',{
        data:{
          appId:this.appId,
          channelId:this.chanlNum,
          page:page || this.tabledata.page,
          pageSize:this.tabledata.size,
          startTime:this.pickTime[0].getTime(),
          endTime:this.pickTime[1].getTime()
        },
        success:(res)=>{
          if(res.success){
            this.tabledata.page = page || this.tabledata.page
            sessionStorage.setItem('dataChannelId',this.chanlNum)
            this.logsDetailData.downloaded = true
            this.tabledata.total = res.object.totalItems
            this.tabledata.list = res.object.contents
            for(let i=0;i<this.tabledata.list.length;i++){
              this.tabledata.list[i].enterDate = this.$utils.formatDate(this.tabledata.list[i].enterTime)
              if(this.tabledata.list[i].firsetTime){
                this.tabledata.list[i].firsetTime = this.$utils.formatDate(this.tabledata.list[i].firsetTime)
              }
              if(this.tabledata.list[i].lastTime){
                this.tabledata.list[i].lastTime = this.$utils.formatDate(this.tabledata.list[i].lastTime)
              }
              if(this.tabledata.list[i].isMobile == 'N'){
                this.tabledata.list[i].terminal = 'PC端'
              }else{
                this.tabledata.list[i].terminal = '移动端'
              }
            }
          }else{
            this.$message.error('观看日志获取失败')
          }
        },
        complete: ()=> {
          this.tabledata.isLoading = false
        }
      })
    },
    resetForm(){
      this.chanlNum = '',
      this.pickTime = ''
    },
  }
};
</script>

<style lang="scss" scoped>
#onlineNum {
  width: 1080px;
  height: 400px;
}
.chanlNum {
  width: 20%;
}
.countUl {
  margin-top: 20px;
  li {
    display: inline-block;
    width: 30%;
    div {
      text-align: center;
      font-size: 1.2rem;
    }
    div:nth-of-type(1) {
      font-weight: bold;
    }
  }
}
.topCountUl{
  margin-top: 20px;
  li {
    display: inline-block;
    width: 24%;
    div{
      text-align: center;
    }
    div:nth-of-type(2){
        font-size:2rem;
        font-weight:bold;
    }
  }
}
#areaCount,
#terminCount {
  float:left;
  width: 700px;
  height: 600px;
  div {
    width: 600px;
  }
}
.datePick {
  height: 36px;
  width: 25%;
}
#countDetail {
  width:400px;
  float: left;
  margin-top: 50px;
}
.chartContain {
  min-width: 1100px;
}
</style>
<style>
.el-tooltip__popper.is-dark{
  width:220px;
}
</style>
